<script setup lang="ts">
import { ref, reactive } from 'vue';
import { ElMessage } from 'element-plus';
import { FormInstance } from 'element-plus';
import { usePersonDetailsStore } from '../../store/person/personDetails';
import user from '../../api/user';
import uploadImg from '../../api/uploadImg';
import utils from '../../utils/utils';
import router from '../../router';
const personDetailsStore = usePersonDetailsStore()
const ruleFormRef = ref();
const ruleFormRefPass = ref();
// 当前激活的 Tab
const activeTab = ref('basic');

// 基本资料表单数据


// 修改密码表单数据
const passwordForm = reactive({
    oldPassword: '',
    newPassword: '',
    confirmPassword: ''
});

// 基本资料表单规则 (示例)
const basicRules = reactive({
    username: [{ required: true, message: '请输入用户昵称', trigger: 'blur' }],
    mobile: [{ required: true, message: '请输入手机号码', trigger: 'blur' }],
    email: [{ required: true, message: '请输入邮箱', trigger: 'blur' }]
});

// 修改密码表单规则 (示例)
const passwordRules = reactive({
    oldPassword: [{ required: true, message: '请输入旧密码', trigger: 'blur' }],
    newPassword: [{ required: true, message: '请输入新密码', trigger: 'blur' }],
    confirmPassword: [{ required: true, message: '请确认新密码', trigger: 'blur' }]
});

// 保存基本资料
const saveBasic = (formEl: FormInstance | undefined) => {
    // TODO: 实现保存基本资料的逻辑
    if (!formEl) return;
    formEl.validate(async (valid) => {
        if (valid) {
            if (personDetailsStore.imgIsSubmit) {
                await uploadImg.uploadImg(personDetailsStore.imgRow).then(res => {
                    console.log(res.data.data);
                    if (res.data.code === 200) {
                        personDetailsStore.PersonalDetails.imgUrl = res.data.data
                        console.log(res.data.data);
                    }
                }).catch(err => {
                    console.log(err);
                })
            }
            personDetailsStore.changeLoading()
            await user.updatePersonalDetail(personDetailsStore.PersonalDetails).then(res => {
                if (res.data.code === 200) {
                    ElMessage.success('基本资料保存成功');
                } else {
                    ElMessage.error(res.data.message);
                }
            }).catch(err => {
                console.log(err);
            })
            await user.getPersonalDetail().then(res => {
                if (res.data.code === 200) {
                    personDetailsStore.setPersonalDetails(JSON.parse(JSON.stringify(res.data.data)))
                    personDetailsStore.PersonalDetailsShow = JSON.parse(JSON.stringify(res.data.data))
                } else {
                    ElMessage.error(res.data.message);
                }
            }).catch(err => {
                console.log(err);
            })
        } else {
            console.log('表单验证失败');
        }
    });
};

// 保存修改密码
const savePassword = (formEl: FormInstance | undefined) => {
    // TODO: 实现修改密码的逻辑
    if (!formEl) return;
    formEl.validate(async (valid) => {
        if (valid) {
            // TODO: 发送修改密码请求
            await user.updatePersonPassword(passwordForm.newPassword, passwordForm.oldPassword, personDetailsStore.PersonalDetails.id).then(res => {
                if (res.data.code === 200) {
                    utils.showMessage(res.data.message, 'success', 2000)
                } 
                if(res.data.code === 407) {
                    utils.showMessage(res.data.message, 'error', 2000)
                }
                if(res.data.code === 408) {
                    utils.showMessage(res.data.message, 'error', 2000)
                }
            }).catch(err => {
                console.log(err);
            }).finally(() => {
                personDetailsStore.changeLoading()
            })
            // 清空表单数据
            passwordForm.oldPassword = '';
            passwordForm.newPassword = '';
            passwordForm.confirmPassword = '';
            router.push('/login')
        } else {
            console.log('表单验证失败');
        }
    });
};

// 关闭当前组件或弹窗 (根据实际使用场景调整)
const closeDialog = () => {
    console.log('关闭');
    // 示例：触发一个自定义事件通知父组件关闭
    // emit('close');
};

</script>

<template>
    <el-card class="personal-edit-card">
        <template #header>
            <div class="card-header">
                <span>基本资料</span>
            </div>
        </template>
        <el-tabs class="demo-tabs" v-model="activeTab" style="padding: 1rem;">
            <el-tab-pane label="基本资料" name="basic">
                <el-form ref="ruleFormRef" :model="personDetailsStore.PersonalDetails" :rules="basicRules"
                    v-loading="personDetailsStore.loading" label-width="80px">
                    <el-form-item label="用户昵称" prop="username">
                        <el-input v-model="personDetailsStore.PersonalDetails.username"
                            placeholder="请输入用户昵称"></el-input>
                    </el-form-item>
                    <el-form-item label="姓名" prop="name">
                        <el-input v-model="personDetailsStore.PersonalDetails.realName" placeholder="请输入姓名"></el-input>
                    </el-form-item>
                    <el-form-item label="手机号码" prop="mobile">
                        <el-input v-model="personDetailsStore.PersonalDetails.mobile" placeholder="请输入手机号码"></el-input>
                    </el-form-item>
                    <el-form-item label="邮箱" prop="email">
                        <el-input v-model="personDetailsStore.PersonalDetails.email" placeholder="请输入邮箱"></el-input>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="saveBasic(ruleFormRef)">保存</el-button>
                        <el-button @click="closeDialog">关闭</el-button>
                    </el-form-item>
                </el-form>
            </el-tab-pane>
            <el-tab-pane label="修改密码" name="password">
                <el-form ref="ruleFormRefPass" :model="passwordForm" :rules="passwordRules" label-width="80px">
                    <el-form-item label="旧密码" prop="oldPassword">
                        <el-input v-model="passwordForm.oldPassword" type="password" placeholder="请输入旧密码"
                            show-password></el-input>
                    </el-form-item>
                    <el-form-item label="新密码" prop="newPassword">
                        <el-input v-model="passwordForm.newPassword" type="password" placeholder="请输入新密码"
                            show-password></el-input>
                    </el-form-item>
                    <el-form-item label="确认密码" prop="confirmPassword">
                        <el-input v-model="passwordForm.confirmPassword" type="password" placeholder="请确认新密码"
                            show-password></el-input>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="savePassword(ruleFormRefPass)">保存</el-button>
                        <el-button @click="closeDialog">关闭</el-button>
                    </el-form-item>
                </el-form>
            </el-tab-pane>
        </el-tabs>
    </el-card>
</template>

<style scoped>
.personal-edit-card {
    max-width: 1000px;
    width: 800px;
    min-width: 500px;
    /* 根据需要调整最大宽度 */
    /* 居中显示 */
}

.card-header {
    font-size: 16px;
    font-weight: bold;
}

@media (max-width: 768px) {
    .personal-edit-card {
        max-width: 100%;
        min-width: 100%;
        /* 在小屏幕上宽度调整为100% */
    }
}

/* 可以根据需要添加更多样式来调整表单布局和间距 */
</style>
